<template>
   <div id="watch-example">
		<p>
			Ask a yes/no question:
			<input nam="question" v-model="question" />
		</p>
		<p>{{ answer }}</p>
	</div>
</template>

<script type="text/javascript">	
	import axios from 'axios'
	import _ from 'lodash'

	export default{
		data(){
			return {
				question: '',
    			answer: 'I cannot give you an answer until you ask a question!'
			}
		},
		created(){
			this.debouncedGetAnswer = _.debounce(this.getAnswer, 500)
		},
		watch: {
			/**
			 * 如果 `question` 发生改变，这个函数就会运行
			 */
			question: function (newQuestion, oldQuestion) {
				this.answer = 'Waiting for you to stop typing...'
				this.debouncedGetAnswer()
			}
		},
		methods:{
			 getAnswer: function () {
				/**
				 * 输入格式为 who is that?
				 */
				if (this.question.indexOf('?') === -1) {
					this.answer = 'Questions usually contain a question mark. ;-)'
					return
				}
				this.answer = 'Thinking...'
				//this指针处理：就我这里我可以使用箭头函数
				var vm = this
				axios.get('https://yesno.wtf/api').then(function (response) {
					vm.answer = _.capitalize(response.data.answer)
				}).catch(function (error) {
					vm.answer = 'Error! Could not reach the API. ' + error
				});
			}
		}
	}
</script>